<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Service,广播,Message,接口,AIDL," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Activity和Service交互的五种方法。">
<meta property="og:type" content="article">
<meta property="og:title" content="Activity和Service交互">
<meta property="og:url" content="http://yoursite.com/2017/03/01/201703/Activity和Service交互/index.html">
<meta property="og:site_name" content="HoneyGuide's Blog">
<meta property="og:description" content="Activity和Service交互的五种方法。">
<meta property="og:image" content="http://yoursite.com/img/201703/aidl.png">
<meta property="og:updated_time" content="2017-03-01T07:17:29.233Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Activity和Service交互">
<meta name="twitter:description" content="Activity和Service交互的五种方法。">
<meta name="twitter:image" content="http://yoursite.com/img/201703/aidl.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'R1W2VDDO1V',
      apiKey: '773854c4c250e5a5cf9cddd97ebcc167',
      indexName: 'Hexo_search',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/01/201703/Activity和Service交互/"/>





  <title> Activity和Service交互 | HoneyGuide's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">﻿<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HoneyGuide's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Stay hungry & Stay young</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">

　　　　　　<!--增加的代码 start-->

          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocapitalize="off" autocomplete="off" autocorrect="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/01/201703/Activity和Service交互/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="HoneyGuide">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HoneyGuide's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Activity和Service交互
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-01T00:00:00+08:00">
                2017-03-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>Activity和Service交互的五种方法。<br><a id="more"></a></p>
<h3 id="1-广播"><a href="#1-广播" class="headerlink" title="1 广播"></a>1 广播</h3><p>Server端(Service)将消息通过广播的方式发送出来，Client端(Activity)注册此广播的监听器，当获取到该广播后，将广播中当前的下载进度解析出来并更新到界面上。</p>
<h4 id="步骤举例"><a href="#步骤举例" class="headerlink" title="步骤举例"></a>步骤举例</h4><ul>
<li>在Client端中通过startService()启动Service。</li>
<li>DownLoadService接到启动的命令之后，执行onCreate()方法，并在其中开启timer计数模拟下载。<br>在Server端的timer计数其中发送广播，告知Client端目前下载进度。</li>
<li>在Client端通过匿名内部类的方式实例化BroadcastReceiver并覆写其中的onReceive()方法。</li>
<li>一定要对Broadcast进行注册和取消注册。只有注册之后相应的broadcast之后才能接收到广播注册方法有两种。</li>
</ul>
<h4 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h4><p>通过广播的方式实现Activity与Service的交互操作简单且容易实现，可以胜任简单级的应用。</p>
<p>但缺点也十分明显，发送广播受到系统制约。系统会优先发送系统级广播，在某些特定的情况下，我们自定义的广播可能会延迟。同时在广播接收器中不能处理长耗时操作，否则系统会出现ANR即应用程序无响应。</p>
<h3 id="2-共享文件交互"><a href="#2-共享文件交互" class="headerlink" title="2 共享文件交互"></a>2 共享文件交互</h3><p>这里提到的共享文件指的是Activity和Service使用同一个文件来达到传递数据的目的。我们使用<strong>SharedPreferences</strong>来实现共享，当然也可以使用其它IO方法实现，通过这种方式实现交互时需要注意，对于文件的读写的时候，同一时间只能一方读一方写，不能两方同时写。</p>
<h4 id="特点-1"><a href="#特点-1" class="headerlink" title="特点"></a>特点</h4><p>对于这种方式实现Activity与Service的交互，可以说很方便，就像使用管道，一个往里写，一个往外读。但这种方式也有缺陷，写入数据较为复杂以及数据量较大时，就有可能导致写入与读数据出不一致的错误。同时因为经过了一个中转站，这种操作将更耗时。</p>
<h3 id="3-Messenger交互"><a href="#3-Messenger交互" class="headerlink" title="3 Messenger交互"></a>3 Messenger交互</h3><p>Messenger引用了一个Handler对象，别人能够向它发送消息(使用mMessenger.send(Message msg)方法)。该类允许跨进程间基于Message通信，在服务端使用Handler创建一个Messenger，客户端只要获得这个服务端的Messenger对象就可以与服务端通信了。也就是说我们可以把Messenger当做Client端与Server端的传话筒，这样就可以沟通交流了。</p>
<h4 id="步骤举例-1"><a href="#步骤举例-1" class="headerlink" title="步骤举例"></a>步骤举例</h4><ul>
<li>在Server端创建信使对象。</li>
<li>Client端使用bindService()绑定Server端。</li>
<li>Server端的onBind()方法返回一个binder对象。</li>
<li>Client端使用返回的binder对象得到Server端信使。</li>
<li><p>获取Server端的信使对象的同时，也初始化Client端的自己的信使对象，并且通过sendMessage()方法发送消息给Server端。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">public void onServiceConnected(ComponentName name, IBinder service) &#123;    </div><div class="line">              rMessenger = new Messenger(service);  　</div><div class="line">    mMessenger = new Messenger(mHandler);//initial the object of local service  </div><div class="line">    sendMessage();  </div><div class="line">　　　  </div><div class="line">             ......  </div><div class="line"> &#125;</div></pre></td></tr></table></figure>
</li>
<li><p>Client端使用获取到的rMessenger来发送消息给Server端，同时将Client端的信使封装到消息中，一并发送给Server端。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">private void sendMessage() &#123;  </div><div class="line">    Message msg = Message.obtain(null, MessengerService.TEST);//MessengerService.TEST=0  </div><div class="line">    msg.replyTo = mMessenger;  </div><div class="line">    try &#123;  </div><div class="line">        rMessenger.send(msg);  </div><div class="line">    &#125; catch (RemoteException e) &#123;  </div><div class="line">        e.printStackTrace();  </div><div class="line">    &#125;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>Server端的Handler对象就能收到消息了，然后可以在其handlerMessage(Message msg)方法中进行处理。</p>
</li>
<li>Client端接收来自Server端的数据。<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">private Handler mHandler = new Handler()&#123;  </div><div class="line">    @Override  </div><div class="line">    public void handleMessage(Message msg) &#123;  </div><div class="line">        super.handleMessage(msg);  </div><div class="line">        switch (msg.what) &#123;  </div><div class="line">        case MessengerService.TEST:  </div><div class="line">            Log.e(TAG, &quot;Get Message From MessengerService. i= &quot;+msg.arg1);  </div><div class="line">            int curLoad = msg.arg1;  </div><div class="line">            mTextView.setText(curLoad+&quot;%&quot;);  </div><div class="line">            mProgressBar.setProgress(curLoad);  </div><div class="line">            break;  </div><div class="line">        default:  </div><div class="line">            break;  </div><div class="line">        &#125;  </div><div class="line">    &#125;  </div><div class="line">&#125;;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>即实现消息的双向传递。</p>
<h4 id="特点-2"><a href="#特点-2" class="headerlink" title="特点"></a>特点</h4><p>通过Messenger来实现Activity和Service的交互，稍微深入一点我们就可以知道，其实Messenger也是通过AIDL来实现的。对於前两种实现方式，Messenger方式总体上来讲也是比较容易理解的，这就和平时使用Handler和Thread通信一个道理。</p>
<h3 id="4-自定义接口交互"><a href="#4-自定义接口交互" class="headerlink" title="4 自定义接口交互"></a>4 自定义接口交互</h3><p>自定义一个接口，该接口中有一个获取当前下载进度的空方法。Server端用一个类继承自Binder并实现该接口，覆写了其中获取当前下载进度的方法。Client端通过ServiceConnection获取到该类的对象，从而能够使用该获取当前下载进度的方法，最终实现实时交互。</p>
<h4 id="步骤"><a href="#步骤" class="headerlink" title="步骤"></a>步骤</h4><ul>
<li>新建一个Interface，并在其中创建一个用于获取当前下载进度的的空方法getCurrentLoad()。</li>
<li><p>新建Server端DownService实现ICountService并在其中通过一个内部类ServiceBinder继承自Binder并实现ICoutService接口。返回当前的下载进度i。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">public interface ICountService &#123;  </div><div class="line">    public int getCurrentLoad();  </div><div class="line">&#125; </div><div class="line"> </div><div class="line">public class DownLoadService extends Service implements ICountService&#123;  </div><div class="line">    private ServiceBinder serviceBinder = new ServiceBinder();    </div><div class="line">    public class ServiceBinder extends Binder implements ICountService&#123;  </div><div class="line">        @Override  </div><div class="line">        public int getCurrentLoad() &#123;  </div><div class="line">            Log.i(TAG, &quot;ServiceBinder getCurrentLoad()... i=:&quot;+i);  </div><div class="line">            return i;  </div><div class="line">        &#125;     </div><div class="line">    &#125;  </div><div class="line">    @Override  </div><div class="line">    public int getCurrentLoad() &#123;  </div><div class="line">        return 0;  </div><div class="line">    &#125;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>Client端使用bindService()绑定Server端。<br>  在Client端绑定Server端的同时，延迟1s开始获取下载进度。其中的intent = new Intent(“com.seven.test”)2com.seven.test该字符串要与在AndroidManifest.xml中申明的一致。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">if (startSerBtn == v) &#123;  </div><div class="line">    Log.i(TAG, &quot;Start Button Clicked.&quot;);  </div><div class="line">    bindService(intent, serConn, BIND_AUTO_CREATE);  </div><div class="line">    timer.schedule(new MyTimerTask(), 1000, TIME * 1000);//这里一定要延迟一下再开始获取数据，不然会报空指针异常  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>Server端返回binder对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">@Override  </div><div class="line">public IBinder onBind(Intent intent) &#123;  </div><div class="line">    Log.i(TAG, &quot;DownLoadService.onBind()...&quot;);  </div><div class="line">    return serviceBinder;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>这里的serviceBinder因为继承了Binder，因此也是Binder对象。</p>
<ul>
<li>Client端通过ServiceConnection来获取Server端的binder对象。<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">private ServiceConnection serConn = new ServiceConnection() &#123;  </div><div class="line">@Override  </div><div class="line">    public void onServiceDisconnected(ComponentName name) &#123;  </div><div class="line">        iCountService = null;  </div><div class="line">    &#125;         </div><div class="line">    @Override  </div><div class="line">    public void onServiceConnected(ComponentName name, IBinder service) &#123;  </div><div class="line">        Log.i(TAG, &quot;onServiceConnected()...&quot;);  </div><div class="line">        iCountService = (ICountService)service;  </div><div class="line">    &#125;  </div><div class="line">&#125;;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>获取的过程是在bindService()过程中完成的，这里的iCountService是接口ICountService的对象，在这里得到实例化。</p>
<ul>
<li><p>在绑定完成之后，Server端会开启下载，bindService()方法执行之后会调用DownLoadService中的onCreate()方法，在其onCreate()方法中开启timer使得i++。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">public void onCreate() &#123;  </div><div class="line">    super.onCreate();  </div><div class="line">    Log.i(TAG, &quot;DownLoadService.onCreate()...&quot;);  </div><div class="line">    timer = new Timer();  </div><div class="line">    timer.schedule(new MyTimerTask(), 0, TIME*1000);  </div><div class="line">&#125;  </div><div class="line">class MyTimerTask extends TimerTask&#123;  </div><div class="line">    @Override  </div><div class="line">    public void run() &#123;  </div><div class="line">        if(100==i)&#123;  </div><div class="line">            i=0;  </div><div class="line">        &#125;  </div><div class="line">        i++;  </div><div class="line">    &#125;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>Server端已经开启了下载，那么Client端需要及时获取下载进度并在主界面上更新。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">Handler mHandler = new Handler()&#123;  </div><div class="line">    @Override  </div><div class="line">    public void handleMessage(Message msg) &#123;  </div><div class="line">        super.handleMessage(msg);  </div><div class="line">        Log.i(TAG, &quot;handleMessage...&quot;);  </div><div class="line">        int curLoad = iCountService.getCurrentLoad();  </div><div class="line">        mProgressBar.setProgress(curLoad);  </div><div class="line">        currentTv.setText(curLoad+&quot;%&quot;);  </div><div class="line">    &#125;  </div><div class="line"> &#125;;  </div><div class="line">class MyTimerTask extends TimerTask&#123;  </div><div class="line">    @Override  </div><div class="line">    public void run() &#123;  </div><div class="line">        mHandler.sendMessage(mHandler.obtainMessage());  </div><div class="line">    &#125;  </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ul>
<p>Client端的Timer在bindService()完成之后1秒再开始获取下载进度，获取方法是直接通过int curLoad = iCountService.getCurrentLoad()；这里的getCurrentLoad()方法是DownLoadService内部类ServiceBinder中的方法。Client端将获取到的下载进度更新到介面上并更新进度条。</p>
<h4 id="特点-3"><a href="#特点-3" class="headerlink" title="特点"></a>特点</h4><p>这种方法简单实用，扩展性强，但其也有一些缺点，比如需要延迟一些再开始获取Server端的数据，从而无法完全实现从零开始同步更新。综其所述，通过自定义接口实现Activity与Service交互的方法还是比较实用的。适用同进程中通信，不能进行跨进程通信。</p>
<h3 id="5-AIDL交互"><a href="#5-AIDL交互" class="headerlink" title="5 AIDL交互"></a>5 AIDL交互</h3><p>AIDL是Android Interface Definition Language的首字母缩写， 也就是Android接口定义语言。提及AIDL就不得不说下Android的服务，Android 支持两种服务类型的服务即本地服务和远程服务。</p>
<p>本地服务无法供在设备上运行的其他应用程序访问，也就是说只能该应用程序内部调用，比如某些应用程序中的下载类服务，这些服务只能由内部调用。而对于远程服务，除了可以由本应用程序调用，还可以允许其他应用程序访问。远程服务一般通过AIDL来实现，可以进行进程间通信，这种服务也就是远程服务。</p>
<p>本地服务与远程服务还是有一些重要的区别。具体来讲，如果服务完全只供同一进程中的组件使用(运行后台任务)，客户端一边通过调用Context.startService()来启动该服务。这种类型的服务为本地服务，它的一般用途是后台执行长耗时操作。而远程服务一般通过bindService()方法启动，主要为不同进程间通信。我们也将远程服务称为AIDL支持服务，因为客户端使用AIDL与服务通信。Android中对于远程服务有多种叫法：远程服务、AIDL服务、外部服务和RPC服务。</p>
<p><img src="/img/201703/aidl.png" alt="image"><br>这属于代理/存根结构，通过这张AIDL的流程图，很容易发现Android实现IPC其实是在原来的C/S框架上加入了代理/存根结构。</p>
<p>比如，你到自动取款机上去取款。那么你就是客户(Client)，取款机就是你的代理(Proxy)；你不会在乎钱具体放在那里，你只想将你的钱从取款机中取出来。你同银行之间的操作完全是取款机代理实现。你的取款请求通过取款机传到另一边，即银行的服务器(Server)。它也没有必要知道你在哪儿取钱，它所关心的是你的身份和你取款多少。当它确认你的权限，就进行相应的操作，返回操作结果给取款机，取款机根据服务器返回结果，从保险柜里取出相应数量的钱给你。你取出卡后，操作完成。取款机不是直接同服务器连接的，他们之间还有一个“存根(Stub)”，取款机与存根通信，服务器与存根通信，从某种意义上说存根就是服务器的代理。</p>
<h4 id="特点-4"><a href="#特点-4" class="headerlink" title="特点"></a>特点</h4><p>AIDL在Android中是进程间通信常用的方式，可能使用较复杂，但效率高，扩展性好。同时很多系统服务就是以这种方式完成与应用程序通信的。</p>
<h3 id="五种交互方式的比较"><a href="#五种交互方式的比较" class="headerlink" title="五种交互方式的比较"></a>五种交互方式的比较</h3><table>
<thead>
<tr>
<th>交互方式</th>
<th>支持跨进程通信</th>
<th>易用性</th>
<th>效率</th>
<th>可扩展性</th>
<th>启动方式</th>
</tr>
</thead>
<tbody>
<tr>
<td>BoardCast</td>
<td>Y</td>
<td>Y</td>
<td>低</td>
<td>低</td>
<td>startService</td>
</tr>
<tr>
<td>SharedPreferences</td>
<td>N</td>
<td>Y</td>
<td>低</td>
<td>低</td>
<td>startService</td>
</tr>
<tr>
<td>Message</td>
<td>Y</td>
<td>N</td>
<td>高</td>
<td>高</td>
<td>bindService</td>
</tr>
<tr>
<td>Interface</td>
<td>N</td>
<td>Y</td>
<td>高</td>
<td>高</td>
<td>bindService</td>
</tr>
<tr>
<td>AIDL</td>
<td>Y</td>
<td>N</td>
<td>高</td>
<td>高</td>
<td>bindService</td>
</tr>
</tbody>
</table>
<h3 id="本地服务和远程服务"><a href="#本地服务和远程服务" class="headerlink" title="本地服务和远程服务"></a>本地服务和远程服务</h3><ul>
<li>本地服务在主进程中，如果主进程被kill，服务也销毁了。</li>
<li>远程服务在另外的进程中，可以为多个进程复用。如一些提供系统服务的Service，在后台常驻。</li>
</ul>
<h3 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h3><ul>
<li>如果采用bindService()方法启动Server端的话，需要通过ServiceConnection()方法来获取Server端返回的binder对象。</li>
<li>在调用 bindService 绑定到Service的时候，应当保证在处理完成之后调用unbindService解除绑定(尽管 Activity 被 finish 的时候绑定会自动解除，并且Service会自动停止)。</li>
<li>使用startService启动服务之后，一定要使用stopService停止服务，不管是否使用bindService。</li>
<li>同时使用 startService 与 bindService 时要注意，Service 的终止，需要unbindService与stopService同时调用才能终止 Service。如果先调用 unbindService 此时服务不会自动终止，再调用stopService之后服务才会停止；如果先调用 stopService 此时服务也不会终止，而在调用 unbindService或者之前调用 bindService的Context不存在了(如Activity 被 finish 的时候)之后服务才会停止。</li>
<li>当设备屏幕在“横”“竖”切换时，此时因为Activity会重新创建，因此旋转之前的使用bindService 建立的连接便会断开(Context 丢失了)，就相当于已经解除绑定了。</li>
</ul>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><p><a href="http://blog.csdn.net/lzt623459815/article/details/8538145/" target="_blank" rel="external">http://blog.csdn.net/lzt623459815/article/details/8538145/</a><br><a href="http://blog.csdn.net/lzt623459815/article/details/8538168" target="_blank" rel="external">http://blog.csdn.net/lzt623459815/article/details/8538168</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Service/" rel="tag"># Service</a>
          
            <a href="/tags/广播/" rel="tag"># 广播</a>
          
            <a href="/tags/Message/" rel="tag"># Message</a>
          
            <a href="/tags/接口/" rel="tag"># 接口</a>
          
            <a href="/tags/AIDL/" rel="tag"># AIDL</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/01/201703/Service进程问题/" rel="next" title="Service进程问题">
                <i class="fa fa-chevron-left"></i> Service进程问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/02/201703/HttpURLConnection/" rel="prev" title="HttpURLConnection">
                HttpURLConnection <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="HoneyGuide" />
          <p class="site-author-name" itemprop="name">HoneyGuide</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">34</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-广播"><span class="nav-number">1.</span> <span class="nav-text">1 广播</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#步骤举例"><span class="nav-number">1.1.</span> <span class="nav-text">步骤举例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#特点"><span class="nav-number">1.2.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-共享文件交互"><span class="nav-number">2.</span> <span class="nav-text">2 共享文件交互</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#特点-1"><span class="nav-number">2.1.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-Messenger交互"><span class="nav-number">3.</span> <span class="nav-text">3 Messenger交互</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#步骤举例-1"><span class="nav-number">3.1.</span> <span class="nav-text">步骤举例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#特点-2"><span class="nav-number">3.2.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-自定义接口交互"><span class="nav-number">4.</span> <span class="nav-text">4 自定义接口交互</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#步骤"><span class="nav-number">4.1.</span> <span class="nav-text">步骤</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#特点-3"><span class="nav-number">4.2.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-AIDL交互"><span class="nav-number">5.</span> <span class="nav-text">5 AIDL交互</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#特点-4"><span class="nav-number">5.1.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五种交互方式的比较"><span class="nav-number">6.</span> <span class="nav-text">五种交互方式的比较</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#本地服务和远程服务"><span class="nav-number">7.</span> <span class="nav-text">本地服务和远程服务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注意事项"><span class="nav-number">8.</span> <span class="nav-text">注意事项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参考"><span class="nav-number">9.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HoneyGuide</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  



  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="local-search-pop-overlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


  

</body>
</html>
